package org.misty.seckill.validator;


import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class MobileValidator implements ConstraintValidator<Mobile, String> {
  /**
   * Pattern对象是线程安全的
   *
   * Instances of this class are immutable and are safe for use by multiple
   * concurrent threads.  Instances of the {@link Matcher} class are not safe for
   * such use.
   */
  private static final Pattern MOBILE_PATTERN = Pattern.compile("^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\\d{8}$");

  private boolean required = false;

  @Override
  public void initialize(Mobile constraintAnnotation) {
    this.required = constraintAnnotation.required();
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    return valid(value, this.required);
  }

  public static boolean valid(String value, boolean required) {
    if (StringUtils.hasText(value)) {
      var matcher = MOBILE_PATTERN.matcher(value);
      return matcher.matches();
    } else {
      return !required;
    }
  }

  public static void main(String[] args) {
    System.out.println(valid(null, false)); // true
    System.out.println(valid("", false)); // true
    System.out.println(valid("   ", false)); // true
    System.out.println(valid("135", false)); // false
    System.out.println(valid("13512341234", false)); // true

    System.out.println("--------------");

    System.out.println(valid(null, true)); // false
    System.out.println(valid("", true)); // false
    System.out.println(valid("   ", true)); // false
    System.out.println(valid("135", true)); // false
    System.out.println(valid("13512341234", true)); // true
  }
}
